//index.js
//获取应用实例
let { api, imgUrl } = require("./../../utils/api.js");
const app = getApp();
let { getTime } = require("./../../utils/constant.js");
let nowDate = getTime().replace(/-/g, "/"); //得到2018/09/08格式的时间
let nowDataUnix = new Date(nowDate).getTime();
let menuTitlePosition = "";

Page({
  data: {
    isGetUserInfo: true,
    imgUrl, //图片链接的前缀
    imgUrls: [],
    hotDish: [{}, {}, {}],
    indicatorDots: true,
    autoplay: true,
    circular: true,
    interval: 3000,
    duration: 1200,
    // typeSetTop: false, //今日菜单中四大类型的tab是否置顶
    score1: "fa fa-star star", //评价星级的class值
    score2: "fa fa-star-half-o half-star",
    score3: "fa fa-star def-star",
    menuTypes: ["荤菜", "素菜", "点心", "水果"],
    menu: [
      [], //今日菜单 之 荤菜集合
      [], //今日菜单 之 素菜集合
      [], //今日菜单 之 点心集合
      [] //今日菜单 之 水果集合
    ],
    selMenuType: 0
  },

  onLoad: function() {
    let that = this;
    this.getClientRect();
    // 查看是否授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting["scope.userInfo"]) {
          // that.setData({
          //   isGetUserInfo: true
          // });
          // // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          // wx.getUserInfo({
          //   success: function(res) {
          //     that.setData({
          //       avatarUrl: res.userInfo.avatarUrl,
          //       nickName: res.userInfo.nickName
          //     });
          //     console.log(res.userInfo);
          //     wx.setStorageSync("userInfo", res.userInfo);
          //   }
          // });
        } else {
          that.setData({
            isGetUserInfo: false
          });
        }
      }
    });
  },

  onShow: function() {
    this.getAllData();
  },

  onPageScroll: function() {
    this.getClientRect(1);
  },
  getClientRect: function(val) {
    let that = this;
    let query = wx.createSelectorQuery(); //electorQuery对象实例
    query
      .select("#menu-title")
      .boundingClientRect(function(rect) {
        // console.log(rect.top);
        if (val === 1) {
          let typeSetTop = false;
          if (rect.top <= -60) {
            if (!that.datatypeSetTop) {
              typeSetTop = true;
            }
          }
          that.setData({
            typeSetTop
          });
        } else {
          menuTitlePosition = rect.top + rect.height;
          // console.log(menuTitlePosition);
        }
      })
      .exec();
  },
  onPullDownRefresh: function() {
    //下拉刷新数据
    this.getAllData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1500);
  },

  getAllData: function() {
    // 获取轮播图信息
    this.getBanner();
    // 获取本周人气榜
    this.getHotDish();
    // 获取今日菜单
    this.getTodayMenu();
  },

  // 获取轮播图信息
  getBanner: function() {
    let that = this;
    wx.request({
      url: api + "showAllBanner.do",
      method: "GET",
      success: function(res) {
        let imgUrls = [];
        if (res.data.status === 1) {
          imgUrls = res.data.data;
        } else {
          imgUrls = [
            { bannerPhoto: "default.jpg" },
            { bannerPhoto: "default.jpg" }
          ];
        }
        that.setData({
          imgUrls
        });
      },
      fail: function(res) {
        console.log("获取轮播图失败:" + res);
      }
    });
  },

  // 获取本周人气榜
  getHotDish: function() {
    let that = this;
    wx.request({
      url: api + "getHotDish.do",
      method: "GET",
      success: function(res) {
        // console.log(res.data);
        if (res.data.status === 1) {
          that.setData({
            hotDish: res.data.data.slice(0, 3)
          });
        }
      },
      fail: function(res) {
        console.log("获取本周人气榜失败:" + res);
      }
    });
  },

  // 最新活动入口
  goActivity: function() {
    wx.navigateTo({
      url: "./../menuVote/menuVote"
    });
  },

  // 获取今日菜单
  getTodayMenu: function() {
    let that = this;
    wx.request({
      url: api + "getCurrentMenu.do",
      method: "GET",
      success: function(res) {
        if (res.data.status === 1) {
          let allMenuData = res.data.data.dishs;
          // 判断获取的菜单是否是今日菜单，如果不是对页面进行往期菜单处理
          if (res.data.data.menuDate !== getTime()) {
            that.setData({
              isOldMenu: true,
              oldMenuDay: res.data.data.menuDate
            });
          } else {
            that.setData({
              isOldMenu: false
            });
          }
          let menu = [
            [], //今日菜单 之 荤菜集合
            [], //今日菜单 之 素菜集合
            [], //今日菜单 之 点心集合
            [] //今日菜单 之 水果集合
          ];
          // console.log(allMenuData);
          for (let i = 0; i < allMenuData.length; i++) {
            //后期进行判断是否是新品 ，是的话设置isNewFood状态
            allMenuData[i].isNewFood = that.judgeNewFood(
              allMenuData[i].timestap
            );
            let category = allMenuData[i].dishCategory - 1; //记录该菜系是什么种类
            menu[category].push(allMenuData[i]);
          }
          // console.log(menu);
          console.log("首页：我刷新了！");
          that.setData({
            menu
          });
        } else {
          wx.showToast({
            title: "今日菜单更新失败，请稍后重试!",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        console.log(res);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
          duration: 2000
        });
      }
    });
  },

  // 判断是否是新品菜系
  judgeNewFood: function(date) {
    if (nowDataUnix - Number(date) < 432000000) {
      return true;
    } else {
      return false;
    }
  },

  // 获取用户信息
  onGetUserInfo: function(e) {
    let info = e.detail.userInfo;
    // console.log(e.detail);
    if (info) {
      // 登录
      wx.login({
        success: function(res) {
          let code = res.code;
          if (code) {
            // 查看是否授权
            wx.getSetting({
              success: function(res) {
                if (res.authSetting["scope.userInfo"]) {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                  wx.getUserInfo({
                    success: function(res) {
                      wx.request({
                        url: api + "wxLogin.do",
                        method: "POST",
                        data: {
                          code,
                          encryptedData: res.encryptedData,
                          iv: res.iv
                        },
                        success: function(res) {
                          console.log(res.data.data);
                          wx.setStorageSync("userInfo", res.data.data);
                        }
                      });
                    }
                  });
                } else {
                  console.log("未授权获取用户信息");
                }
              }
            });
          } else {
            console.log("登录失败！" + res.errMsg);
          }
        }
      });
      this.setData({
        avatarUrl: info.avatarUrl,
        nickName: info.nickName,
        isGetUserInfo: true
      });
    }
  },

  // 选择菜系类型
  selTypeTab: function(e) {
    // console.log(e.currentTarget.dataset.typename);
    let { typename, scroll } = e.currentTarget.dataset;
    if (scroll === "true") {
      wx.pageScrollTo({
        scrollTop: menuTitlePosition,
        duration: 300
      });
    }
    this.setData({
      selMenuType: typename
    });
  },
  // 遮罩控制
  preventD: function() {},

  // 图片预览
  imgPreview: function(e) {
    let src = e.currentTarget.dataset.src;
    let srcArr = [src];
    let current = src;
    if (Object.prototype.toString.call(src) == "[object Array]") {
      srcArr = src.map(val => {
        return imgUrl + val;
      });
      current = e.currentTarget.dataset.current;
    }
    wx.previewImage({
      current,
      urls: srcArr // 需要预览的图片http链接列表
    });
  },

  goDetails: function(e) {
    let dishId = e.currentTarget.dataset.dishid; //data-dishId会大写转小写
    wx.navigateTo({
      url: "./../details/details?dishId=" + dishId
    });
  }
});
